﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Kooboo.Web.Areas.Commerce.Controllers
{
    using Kooboo;
    using Kooboo.Commerce;
    using Kooboo.Commerce.AddIn;
    
    using Kooboo.Globalization;
    using Kooboo.IoC;
    
    using Kooboo.Web.Mvc;
    using Kooboo.Commerce.Contexts.Payments;


    public class PaymentController : ManagementController
    {
        public ActionResult Index()
        {
            var payments = this.Actor.QueryPayments()
                .OrderBy(i => i.MethodName)
                .AsEnumerable();

            ViewData["sync_action"] = this.Url.Action<PaymentController>(i => i.Sync());

            return View("Index", payments);
        }

        public ActionResult Edit(string name)
        {
            var payment = this.Actor.QueryPayments()
                .FirstOrDefault(i => i.MethodName == name);

            if (payment == null)
            {
                var method = ObjectContainer.CreateInstances<IPaymentMethod>()
                    .FirstOrDefault(i => i.Name == name);

                payment = ObjectContainer.CreateInstance<IPayment>();
                payment.MethodName = name;
                payment.HeadLine = method.HeadLine;
                payment.IsEnable = false;
                payment.IsRedirect = true;

                this.Actor.Post(payment);
            }
         
            
            ViewData["IsDirectPaymentMethod"] = payment.FindMethod() is IDirectPaymentMethod;

            return View(payment);
        }

        [HttpPost]
        public ActionResult Edit(IPayment payment, string next)
        {

            if (ModelState.IsValid)
            {
                payment.CheckMethod();
                this.Actor.Put(payment);
                
                if (next == "next-action")
                {
                    return this.Redirect(this.Url.Action<PaymentController>(i => i.Settings(payment.MethodName)));
                }
                else
                {
                    return this.Redirect(this.Url.Action<PaymentController>(i => i.Index()));
                }
            }
            else
            {
                return Json(new {Message=ModelState.GetErrorMessages() });
            }
            


        }


        public ActionResult Settings(string name)
        {
            var payment = this.Actor
                .QueryPayments()
                .Where(i => i.MethodName.ToLower() == name.ToLower())
                .FirstOrDefault();

            var method = payment.FindMethod();

            return method.Views.Settings();
        }

        public ActionResult Sync()
        {
            ServiceHost host = new ServiceHost();
            host.SyncPayments();

            return this.RedirectToAction("Index");
        }

    }
}
